@file:OptIn(ExperimentalMaterial3Api::class)

package com.fishingwithme.android.ui.screens.circle

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.data.model.Position
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.components.ImageUploader
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.AddCircleModel
import com.fishingwithme.android.utils.EventBus
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddCircleScreen(
    navController: NavController,
    viewModel: AddCircleModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val coroutineScope = rememberCoroutineScope()

    // 监听地图数据事件
    LaunchedEffect(Unit) {
        coroutineScope.launch {
            try {
                EventBus.mapDataEvent.collect { event ->
                    val mapData = event.data

                    if (mapData.containsKey("polygonPoints")) {
                        val navPoints = mapData["polygonPoints"] as? List<*>
                        if (navPoints != null && navPoints.isNotEmpty()) {
                            viewModel.updatePoints(navPoints as List<Position>)

                        }
                    }
                }
            } catch (e: Exception) {
                android.util.Log.e("AddCircleScreen", "${e.message}")
            }
        }
    }

    // 监听保存成功状态
    LaunchedEffect(uiState.isSaveSuccess) {
        if (uiState.isSaveSuccess && !uiState.isLoading) {
            navController.popBackStack()
            viewModel.resetSaveState()
        }
    }

    suspend fun onPictureUpload(file: File): Flow<Result<String>> {
        return viewModel.uploadFile(file)
    }

    Scaffold(
        containerColor = MaterialTheme.colorScheme.background
    ) { paddingValues ->
        Box(modifier = Modifier.fillMaxSize()) {
            // 表单内容
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(AppDimensions.SPACING_16),
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_16),
                content = {
                    // 圈子标题
                    item {
                        OutlinedTextField(
                            value = uiState.title,
                            onValueChange = { viewModel.updateTitle(it) },
                            label = {
                                Text(
                                    "圈子标题",
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            enabled = !uiState.isLoading,
                            colors = TextFieldDefaults.outlinedTextFieldColors(
                                focusedTextColor = MaterialTheme.colorScheme.onSurface,
                                unfocusedTextColor = MaterialTheme.colorScheme.onSurface,
                                cursorColor = MaterialTheme.colorScheme.primary,
                                focusedBorderColor = MaterialTheme.colorScheme.primary,
                                unfocusedBorderColor = MaterialTheme.colorScheme.outline
                            )
                        )
                    }
                    // 照片上传
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_8)) {
                                ImageUploader(
                                    pictures = uiState.pics,
                                    maxImages = 5,
                                    onPicturesChanged = { newPictures ->
                                        if (!uiState.isLoading) {
                                            viewModel.updatePics(newPictures)
                                        }
                                    },
                                    onImageUpload = { file ->
                                        onPictureUpload(file)
                                    }
                                )
                            }
                        }
                    }

                    // 位置信息
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                                // 显示当前选择的经纬度
                                if (uiState.latitude != 0.0 && uiState.longitude != 0.0) {
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Column {
                                            Text("纬度: ${uiState.latitude}")
                                            Text("经度: ${uiState.longitude}")
                                        }
                                    }
                                }

                                // 操作按钮
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.End,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    // 跳转到地图选择按钮
                                    Button(
                                        onClick = {
                                            if (!uiState.isLoading) {
                                                val router =
                                                    "${FishingNavigation.MAP_SELECTION}?moduleKey=addCircle"
                                                navController.navigate(router)
                                            }
                                        },
                                        enabled = !uiState.isLoading,
                                        modifier = Modifier.padding(AppDimensions.SPACING_8)
                                    ) {
                                        Text("在地图上选择")
                                    }
                                }
                            }
                        }
                    }

                    // 圈子描述
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                                OutlinedTextField(
                                    value = uiState.description,
                                    onValueChange = { viewModel.updateDescription(it) },
                                    label = { Text("圈子描述") },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(AppDimensions.CARD_HEIGHT_150),
                                    maxLines = 10,
                                    enabled = !uiState.isLoading
                                )
                            }
                        }
                    }
                    // 提交按钮
                    item {
                        Button(
                            onClick = {
                                viewModel.addCircle()
                                      },
                            enabled = uiState.title.isNotBlank() &&
                                    uiState.latitude != 0.0 && uiState.longitude != 0.0 &&
                                    uiState.pics.isNotEmpty() &&
                                    !uiState.isLoading,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text("创建圈子")
                        }
                    }
                }
            )

            // 加载遮罩
            if (uiState.isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background.copy(alpha = 0.7f))
                        .clickable(enabled = false) {},
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.size(AppDimensions.ICON_SIZE_48)
                    )
                }
            }

            // 错误提示
            if (uiState.error != null) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background.copy(alpha = 0.7f))
                        .clickable(enabled = false) {},
                    contentAlignment = Alignment.Center
                ) {
                    Card(
                        modifier = Modifier.padding(AppDimensions.SPACING_16),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        )
                    ) {
                        Column(
                            modifier = Modifier.padding(AppDimensions.SPACING_16),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = uiState.error!!,
                                color = MaterialTheme.colorScheme.onErrorContainer
                            )
                            Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))
                            Button(
                                onClick = { viewModel.clearError() }
                            ) {
                                Text("确定")
                            }
                        }
                    }
                }
            }
        }
    }
}